package com.nmgs.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.nmgs.entity.UserTokenentity;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.nmgs.entity.UserTable;
@Slf4j
public class TokenUtil {
    /**
     * token秘钥
     */
    private static final String TOKEN_SECRET = "apiManager";

    /**
     * 设置过期时间
     */
    private static final long EXPIRE_DATE = 30 * 60 * 1000;

    public static String token(UserTable user) {

        String token = "";
        try {
            //过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIRE_DATE);
            //秘钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String, Object> header = new HashMap<>();
            header.put("typ", "JWT");
            header.put("alg", "HS256");
            //携带username，password信息，生成签名
            token = JWT.create()
                    .withHeader(header)
                    .withClaim("Man", user.getMan())
                    .withClaim("Manid", user.getManid())
                    .withClaim("Manno", user.getManno())
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (Exception e) {
            log.error("获取token异常", e);
            return null;
        }
        return token;
    }

    public static UserTokenentity verify(String token) {
        /**
         * @desc 验证token，通过返回true
         * @params [token]需要校验的串
         **/
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            UserTable user = new UserTable();
            user.setManno(jwt.getClaim("Manno").toString().replaceAll("\\\"",""));
            user.setMan(jwt.getClaim("Man").toString().replaceAll("\\\"",""));
            user.setManid(Integer.parseInt(jwt.getClaim("Manid").toString()));
            UserTokenentity entity=new UserTokenentity();
            entity.setUser(user);
            entity.setToken(token(user));
            return entity;
        } catch (Exception e) {
            log.error("验证token异常", e);
            return null;
        }
    }

    public static boolean verify(String token, HttpServletRequest request) {
        /**
         * @desc 验证token，通过返回true
         * @params [token]需要校验的串
         **/
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            HttpSession session = request.getSession();
            if (session.getAttribute("token") == null || session.getAttribute("token").equals("")) {
                UserTable user = null;
                try {
                    if (jwt.getClaim("Manno").toString().equals("0")||jwt.getClaim("Manno").toString().equals("admin")) {
                        user = new UserTable();
                        user.setManno("admin");
                        user.setMan("管理员");
                        user.setManid(-1);
                    } else {
                        user = new UserTable();
                        user.setManno(jwt.getClaim("manno").toString());
                        user.setMan(jwt.getClaim("man").toString());
                        user.setManid(Integer.parseInt(jwt.getClaim("manid").toString()));
                        //user = userservice.selectUserByLoginName(Long.parseLong(jwt.getClaim("Manno").toString().replaceAll("\\\"","")));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                session.setAttribute("token", token);
                session.setAttribute("user", user);
            }
            return true;
        } catch (Exception e) {
            log.error("验证token异常", e);
            return false;
        }
    }

    public static String getTokenParams(String token, String key) {
        /**
         * @desc 验证token，通过返回true
         * @params [token]需要校验的串
         **/
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaim(key).toString();
        } catch (Exception e) {
            log.error("验证token异常", e);
            return "";
        }
    }

    public static String reToken(String token) {
        /**
         * @desc 验证token，通过返回true
         * @params [token]需要校验的串
         **/
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            String Man = jwt.getClaim("Man").toString();
            String Manid = jwt.getClaim("Manid").toString();
            String Manno = jwt.getClaim("Manno").toString();
            //过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIRE_DATE);
            //秘钥及加密算法
            //设置头部信息
            Map<String, Object> header = new HashMap<>();
            header.put("typ", "JWT");
            header.put("alg", "HS256");
            //携带username，password信息，生成签名
            token = JWT.create()
                    .withHeader(header)
                    .withClaim("Man", Man)
                    .withClaim("Manid", Manid)
                    .withClaim("Manno", Manno)
                    .withExpiresAt(date)
                    .sign(algorithm);
            return token;
        } catch (Exception e) {
            log.error("获取token异常", e);
            return "";
        }
    }

    public static Object getTokenParams(String token) {
        /**
         * @desc 验证token，通过返回true
         * @params [token]需要校验的串
         **/
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaims();
        } catch (Exception e) {
            log.error("验证token异常", e);
            return "";
        }
    }

    public static String reToken(String token, HttpServletRequest request) {
        /**
         * @desc 验证token，通过返回true
         * @params [token]需要校验的串
         **/
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            String Man = jwt.getClaim("Man").toString().replaceAll("\\\"","");
            String Manid = jwt.getClaim("Manid").toString().replaceAll("\\\"","");
            String Manno = jwt.getClaim("Manno").toString().replaceAll("\\\"","");
            //过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIRE_DATE);
            //秘钥及加密算法
            //设置头部信息
            Map<String, Object> header = new HashMap<>();
            header.put("typ", "JWT");
            header.put("alg", "HS256");
            //携带username，password信息，生成签名
            token = JWT.create()
                    .withHeader(header)
                    .withClaim("Man", Man)
                    .withClaim("Manid", Manid)
                    .withClaim("Manno", Manno)
                    .withExpiresAt(date)
                    .sign(algorithm);
            HttpSession session = request.getSession();
            session.setAttribute("Man", Man);
            session.setAttribute("Manid", Manid);
            session.setAttribute("Manno", Manno);
            session.setAttribute("token", token);
            return token;
        } catch (Exception e) {
            log.error("获取token异常", e);
            return "";
        }
    }
}